package com.skynet.springboot.mybatis.springmybatis.aspect;

import com.google.gson.Gson;
import com.skynet.springboot.mybatis.springmybatis.annotation.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author Skynet
 * @Date 2017/9/9-22:35.
 */
@Component
@Aspect
public class LogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("@annotation(com.skynet.springboot.mybatis.springmybatis.annotation.Log)")
    public void logPointCut(){}

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        long startTime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - startTime;

        //保存到日志表
        saveLog(joinPoint,time);

        return result;
    }

    private void saveLog(ProceedingJoinPoint joinPoint, long time) {
        LOGGER.info("************开始打印日志************");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        Log log = method.getAnnotation(Log.class);
        if(log != null){
            //注解上的描述
            LOGGER.info("描述：{}",log.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        LOGGER.info("类名：{}，方法名：{}",className,methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        LOGGER.info("参数 {}", new Gson().toJson(args));
        LOGGER.info("************执行时间：{}毫秒************",time);
    }

}
